﻿using System;
using System.Globalization;
using Gumini.JulaDB.Provider;

namespace Gumini.JulaDB.Test.Common
{
    public class PersonTestDataCreator
    {
        private readonly JulaDbConnection _connection;

        private void AddPerson(string firstName, string lastName, decimal? age)
        {
            _connection.ExecuteValidNonQuery(String.Format("insert into person (Id, FirstName, LastName, Age) values ({0}, '{1}', '{2}', {3})",
                TotalPersonCount, firstName, lastName, (age != null ? age.Value.ToString(CultureInfo.InvariantCulture) : "null")));
            TotalPersonCount++;
            if (age != null)
            {
                AgeNotNullPersonCount++;
                decimal ageValue = age.Value;
                SumAge += ageValue;
                if (age < MinAge)
                {
                    YoungestPersonFirstName = firstName;
                    YoungestPersonLastName = lastName;
                    MinAge = ageValue;
                }
                if (age > MaxAge)
                {
                    OldestPersonFirstName = firstName;
                    OldestPersonLastName = lastName;
                    MaxAge = ageValue;
                }
            }
        }

        public PersonTestDataCreator(JulaDbConnection connection)
        {
            _connection = connection;

            TotalPersonCount = 0;
            AgeNotNullPersonCount = 0;
            SumAge = 0;
            MinAge = decimal.MaxValue;
            MaxAge = decimal.MinValue;

            new JulaDbCommand(
              @"create table Person
                (
                    Id int,
                    FirstName varchar(100),
                    LastName varchar(100),
                    Age decimal
                )", connection).ExecuteNonQuery();

            AddPerson("Jan", "Kowalski", 12.4M);
            AddPerson("Anna", "Nowak", 24.1M);
            AddPerson("Jan", "Nowak", 55.9M);
            AddPerson("Marek", "Kowalski", 45M);
            AddPerson("Tomasz", "Kowalski", null);
            AddPerson("Tomasz", "Nowak", 72.7M);
            AddPerson("Maria", "Kowalska", 11.5M);
        }

        public decimal TotalPersonCount { get; private set; }
        public decimal AgeNotNullPersonCount { get; private set; }
        public decimal SumAge { get; private set; }
        public decimal MinAge { get; private set; }
        public decimal MaxAge { get; private set; }
        public string YoungestPersonFirstName { get; private set; }
        public string YoungestPersonLastName { get; private set; }
        public string OldestPersonFirstName { get; private set; }
        public string OldestPersonLastName { get; private set; }
        public decimal AverageAge
        {
            get { return SumAge / AgeNotNullPersonCount; }
        }
    }
}
